package com.itheima.health.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @DubboReference
    private UserService userService;

    /**
     * @Author: 15041
     * @Date: 18:27 2021/1/18
     * @Parms: [userName]
     * @ReturnType: org.springframework.security.core.userdetails.UserDetails
     *Description: 用户登录获取数据库用户
    */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //模拟从数据库读取用户信息 从上面的user中获取用户信息
        User user = userService.findByUserName(userName);
        if (null == user){//如果user不存在抛出异常
            throw new UsernameNotFoundException("用户不存在");
        }
        //如果存在获取用户的名字和密码
        String username = user.getUsername();
        String password = user.getPassword();

        //获取用户角色及权限
        Collection<GrantedAuthority> authList = new ArrayList<>();
        for (Role role : user.getRoles()) {
            //角色关键词
            ((ArrayList<GrantedAuthority>) authList).add(new SimpleGrantedAuthority(role.getKeyword()));
            for (Permission permission : role.getPermissions()) {
                //权限关键词
                authList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        log.info("获取用户认证权限信息 userName:{},authorities:{}",username,authList);

        return new org.springframework.security.core.userdetails.User(username,password,authList);
    }
}
